package com.example.playnote.activity.ui

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.playnote.R
import com.example.playnote.activity.login.LoginActivity
import com.example.playnote.adapter.SearchAdapter
import com.example.playnote.base.BaseActivity
import com.example.playnote.bean.Constant
import com.example.playnote.bean.Datas
import com.example.playnote.bean.HomeListResponse
import com.example.playnote.bean.ToastFlag
import com.example.playnote.databinding.ActivitySearchBinding
import com.example.playnote.toasty
import com.example.playnote.utils.MMKVUtils
import com.example.playnote.viewModel.HomeViewModel

class SearchActivity: BaseActivity<HomeViewModel, ActivitySearchBinding>() {

    private var searchData: List<Datas>? = null

    /**
     * adapter
     */
    private val searchAdapter: SearchAdapter by lazy {
        SearchAdapter(this, searchData)
    }
    /**
     * SearView
     */
    private var searchView: SearchView? = null
    /**
     * Search key
     */
    private var searchKey: String? = null
    /**
     * true search, false like
     */
    private var isSearch: Boolean = true
    /**
     * true like, false bookmark
     */
    private var isLike: Boolean = true
    /**
     * check login for SharedPreferences
     */
    private val isLogin: Boolean by lazy {
        MMKVUtils.getBoolean(Constant.LOGIN_KEY)?:false
    }
    override fun initView(savedInstanceState: Bundle?) {
        intent.extras?.let {
            isSearch = it.getBoolean(Constant.SEARCH_KEY, true)
            isLike = it.getBoolean(Constant.LIKE_KEY, true)
        }
        mDatabind.toolbar.run {
            title =
                if (isSearch) "" else if (isLike) getString(R.string.my_like) else getString(R.string.my_bookmark)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        mDatabind.swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        mDatabind.recyclerView.run {
            layoutManager = LinearLayoutManager(this@SearchActivity)
            adapter = searchAdapter
        }
        searchAdapter.run {
            bindToRecyclerView(mDatabind.recyclerView)
            setOnLoadMoreListener({
                val page = searchAdapter.data.size / 20 + 1
                if (!isSearch) {
                    mViewModel.getLikeList()
                } else {
                    searchKey?.let {
                        mViewModel.getSearchList(page, it)
                    }
                }
            }, mDatabind.recyclerView)
            onItemClickListener = this@SearchActivity.onItemClickListener
            onItemChildClickListener = this@SearchActivity.onItemChildClickListener
            setEmptyView(R.layout.fragment_home_empty)
        }
        if (!isSearch) {
            mViewModel .getLikeList()
        } else {
            intent.extras?.let {
                searchKey = it.getString(Constant.CONTENT_TITLE_KEY, null)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.searchList.observe(this) {
            if (it.errorCode != 0) {
                getSearchListFailed(it.errorMsg)
                return@observe
            }
            // 列表总数
            val total = it.data.total
            if (total == 0) {
                getSearchListZero()
                return@observe
            }
            // 当第一页小于一页总数时
            if (total < it.data.size) {
                getSearchListSmall(it.data)
                return@observe
            }
            searchData = it.data.datas
            getSearchListSuccess(it.data)
        }
        mViewModel.likeList.observe(this) {result->
            if (result.errorCode != 0) {
                getLikeListFailed(result.errorMsg)
                return@observe
            }
            // 列表总数
            val total = result.data.total
            if (total == 0) {
                getLikeListZero()
                return@observe
            }
            // 当第一页小于一页总数时
            if (total < result.data.size) {
                getLikeListSmall(result.data)
                return@observe
            }
            getLikeListSuccess(result.data)
        }
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (searchData?.size != 0) {
            Intent(this, ContentActivity::class.java).run {
                putExtra(Constant.CONTENT_URL_KEY, searchData!![position].link)
                putExtra(Constant.CONTENT_TITLE_KEY, searchData!![position].title)
                startActivity(this)
            }
        }
    }
    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
        BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            if (searchData?.size != 0) {
                val data = searchData!![position]
                when (view.id) {
                    R.id.homeItemType -> {
                        data.chapterName ?: let {
                            it.toasty(ToastFlag.ERROR, "类别为空")
                            return@OnItemChildClickListener
                        }
                        Intent(this, TypeContentActivity::class.java).run {
                            putExtra(Constant.CONTENT_TARGET_KEY, true)
                            putExtra(Constant.CONTENT_TITLE_KEY, data.chapterName)
                            putExtra(Constant.CONTENT_CID_KEY, data.chapterId)
                            startActivity(this)
                        }
                    }
                    R.id.homeItemLike -> {
                        if (!isLogin) {
                            Intent(this, LoginActivity::class.java).run {
                                startActivity(this)
                            }
                            this.toasty(ToastFlag.ERROR,getString(R.string.login_please_login))
                            return@OnItemChildClickListener
                        }
                        if (!isSearch) {
                            // delete data
                            searchAdapter.remove(position)
                            mViewModel.collectArticle(data.id, false)
                        } else {
                            val collect = data.collect
                            data.collect = !collect
                            searchAdapter.setData(position, data)
                            mViewModel.collectArticle(data.id, !collect)
                        }
                    }
                }
            }
        }

    override fun initImmersionBar() {
        super.initImmersionBar()
        immersionBar.titleBar(mDatabind.toolbar).init()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        if (isSearch) {
            menuInflater.inflate(R.menu.menu_search, menu)
            // get SearchView
            searchView = menu.findItem(R.id.menuSearch).actionView as SearchView
            // init SearchView
            searchView?.init(1920, false, onQueryTextListener = onQueryTextListener)
            searchKey?.let {
                searchView?.setQuery(it, true)
            }
        }
        return super.onCreateOptionsMenu(menu)
    }
    /**
     * QueryListener
     */
    private val onQueryTextListener = object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            query?.let {
                searchKey = it
                mDatabind.swipeRefreshLayout.isRefreshing = true
                searchAdapter.setEnableLoadMore(false)
                mViewModel.getSearchList(k = it)
            } ?: let {
                mDatabind.swipeRefreshLayout.isRefreshing = false
                this@SearchActivity.toasty(ToastFlag.SUCCESS, getString(R.string.search_not_empty))
            }
            searchView?.clearFocus()
            return false
        }

        override fun onQueryTextChange(newText: String?): Boolean = false
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // back clickListener
        if (item.itemId == android.R.id.home) {
            // remove focus
            searchView?.clearFocus()
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * init SearchView
     */
    private fun SearchView.init(
        sMaxWidth: Int = 0,
        sIconified: Boolean = false,
        isClose: Boolean = false,
        onQueryTextListener: SearchView.OnQueryTextListener
    ) = this.run {
        if (sMaxWidth != 0) {
            maxWidth = sMaxWidth
        }
        // false open
        isIconified = sIconified
        // not close
        if (!isClose) {
            // open
            onActionViewExpanded()
        }
        // search listener
        setOnQueryTextListener(onQueryTextListener)
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        if (!isSearch) {
            searchAdapter.setEnableLoadMore(false)
            mDatabind.swipeRefreshLayout.isRefreshing = true
            mViewModel.getLikeList()
            return@OnRefreshListener
        }
        searchKey?.let {
            searchAdapter.setEnableLoadMore(false)
            mDatabind.swipeRefreshLayout.isRefreshing = true
            mViewModel.getSearchList(k = it)
        } ?: let {
            mDatabind.swipeRefreshLayout.isRefreshing = false
            this.toasty(ToastFlag.ERROR, getString(R.string.search_not_empty))
        }
    }

    private fun getSearchListSuccess(result: HomeListResponse) {
        result.datas.let {
            searchAdapter.run {
                // 列表总数
                val total = result.total
                // 当前总数
                if (result.offset >= total || data.size >= total) {
                    loadMoreEnd()
                    return@let
                }
                if (mDatabind.swipeRefreshLayout.isRefreshing) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                loadMoreComplete()
                setEnableLoadMore(true)
            }
        }
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

    private fun getSearchListFailed(errorMessage: String?) {
        searchAdapter.setEnableLoadMore(false)
        mDatabind.swipeRefreshLayout.isRefreshing = false
        searchAdapter.loadMoreFail()
        this.toasty(ToastFlag.ERROR, content = errorMessage?:getString(R.string.get_data_error))
    }

    private fun getSearchListZero() {
        this.toasty(
            ToastFlag.ERROR,
            content = if (isSearch) getString(R.string.search_failed_not_article) else getString(R.string.get_data_zero)
        )
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

    private fun getSearchListSmall(result: HomeListResponse) {
        result.datas.let {
            searchAdapter.run {
                replaceData(it)
                loadMoreEnd()
                loadMoreComplete()
                setEnableLoadMore(false)
            }
        }
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

    private fun getLikeListSuccess(result: HomeListResponse) {
        result.datas.let {
            searchAdapter.run {
                // 列表总数
                val total = result.total
                // 当前总数
                if (result.offset >= total || data.size >= total) {
                    loadMoreEnd()
                    return@let
                }
                if (mDatabind.swipeRefreshLayout.isRefreshing) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                loadMoreComplete()
                setEnableLoadMore(true)
            }
        }
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

    private fun getLikeListFailed(errorMessage: String?) {
        searchAdapter.setEnableLoadMore(false)
        mDatabind.swipeRefreshLayout.isRefreshing = false
        searchAdapter.loadMoreFail()
        this.toasty(ToastFlag.ERROR, errorMessage ?: getString(R.string.get_data_error))
    }

    private fun getLikeListZero() {
        this.toasty(
            ToastFlag.ERROR,
            content = if (isSearch) getString(R.string.search_failed_not_article) else getString(R.string.get_data_zero)
        )
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

    private fun getLikeListSmall(result: HomeListResponse) {
        result.datas.let {
            searchAdapter.run {
                replaceData(it)
                loadMoreEnd()
                loadMoreComplete()
                setEnableLoadMore(false)
            }
        }
        mDatabind.swipeRefreshLayout.isRefreshing = false
    }

}